<?php
namespace app\admin;

use pidan\App;
use pidan\Response;
use pidan\Validate;


/**
 * 控制器基础类
 */
abstract class Controller
{
	protected $app;

	protected $request;

	protected $model;

	/**
	 * 构造方法
	 * @access public
	 * @param App $app 应用对象
	 */
	public function __construct()
	{
		$this->initialize();

		$this->app=$app = app();$this->request=$request=$app->make('request');

		#$app->lang->load($app->getAppPath() . 'lang/' . $app->lang->getLangSet() . '/' . $app->http->getName() . '.php');//加载app_name语言包

		//是否登陆  不是提交登陆检查$access_token,无效退出登陆  终止访问
		if(!in_array($request->action(),['cache','login'])){
			if(!token_session('?admin_id')){
				($response=$this->code(1001))->send();
				$app->http->end($response);
				exit;
			}
		}
	}


	// 初始化
	protected function initialize()
	{
	}
	protected function adminLog($add = ''){
			$data =array(
					'admin_id'=>token_session('admin_id'),
					'username'=>token_session('admin_username'),
					'useragent'=>$_SERVER['HTTP_USER_AGENT'],
					'url'=>$_SERVER['REQUEST_URI'],
					'title'=>$add,
					'ip'=>$this->request->ip()
			);
			$db=new \app\admin\model\AdminLog;
			$db->save($data);
			#Db::name('admin_log')->save($data);
	}



	protected function code($code,string $msg='',array $result=[]){
		return $this->result(['code'=>$code,'msg'=>$msg,'data'=>$result]);
	}

	protected function api($data,int $code=0,string $msg=''){
		return $this->result(['code'=>$code,'msg'=>$msg,'data'=>$data]);
	}
	protected function lists($data,$count,int $code=0,string $msg=''){
		return $this->result(['code'=>$code,'msg'=>$msg,'count'=>$count,'data'=>$data]);
	}


	/**
	 * 操作成功跳转的快捷方法
	 * @access protected
	 * @param mixed $msg 提示信息
	 * @param string $url 跳转的URL地址
	 * @param mixed $data 返回的数据
	 * @param integer $wait 跳转等待时间
	 * @param array $header 发送的Header信息
	 * @return void
	 */
	protected function success($msg = '', $data = '', $type = 'html', string $url = null, int $wait = 3, array $header = [], int $code = 1){
		if (is_null($url) && isset($_SERVER["HTTP_REFERER"])) {
			$url = $_SERVER["HTTP_REFERER"];
		} elseif ($url) {
			$url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : $this->app->route->buildUrl($url);
		}
		$assign = [
			'code' => $code,
			'msg' => $msg,
			'data' => $data,
			'url' => $url,
			'wait' => $wait,
		];

		// 把跳转模板的渲染下沉，这样在 response_send 行为里通过getData()获得的数据是一致性的格式
		if ('html' == strtolower($type)) {
			include config('jump.jump_tpl');
			$response = Response::create(ob_get_clean(), 'html')->header($header);
		} else {
			$response = Response::create($assign, $type)->header($header);
		}
		return $response;
	}

	protected function error($msg = '', $data = '', $type = 'html', string $url = null, int $wait = 3, array $header = [], int $code = 0){
		return $this->success($msg, $data, $type, $url, $wait, $header, $code);
	}

	/**
	 * 返回封装后的API数据到客户端
	 * @access protected
	 * @param mixed $data 要返回的数据
	 * @param integer $code 返回的code
	 * @param mixed $msg 提示信息
	 * @param string $type 返回数据格式
	 * @param array $header 发送的Header信息
	 * @return void
	 */
	protected function result($result, $type = 'json', array $header = []){
		return Response::create($result, $type)->header($header);
	}

	/**
	 * URL重定向
	 * @access protected
	 * @param string $url 跳转的URL表达式
	 * @param integer $code http code
	 * @param array $with 隐式传参
	 * @return void
	 */
	protected function redirect($url, $code = 302, $with = []){
		return Response::create($url, 'redirect')->code($code)->with($with);
	}

	/**
	 * @param array $data 验证数据
	 * @param $validate   验证类
	 * @param $scene   验证场景
	 */
	public function validate(array $data, $validate, $scene = ''){
		try {
			$class = new $validate;
			if (!empty($scene)) {
				$res = $class->scene($scene)->check($data);
			} else {
				$res = $class->check($data);
			}
			if (!$res) {
				return $this->code(1, $class->getError());
			} else
				return $this->code(0);

		} catch (\Exception $e) {
			return $this->code(2, $class->getError());
		}
	}
}
